package com.mybatis.lo.handler;

import com.mybatis.lo.config.MappedStatement;
import com.mybatis.lo.mapping.BoundSql;
import com.mybatis.lo.mapping.ParameterMapping;
import com.mybatis.lo.registry.SimpleTypeRegistry;
import com.mybatis.lo.utils.OgnlUtils;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

/**
 * 默认的参数设置器
 * @author zhangbh
 * 2023-06-20 09:27
 **/
public class DefaultParameterHandler implements ParameterHandler {
    private final MappedStatement mappedStatement;
    private final BoundSql boundSql;
    private final Object param;

    public DefaultParameterHandler(MappedStatement mappedStatement, BoundSql boundSql, Object param) {
        this.mappedStatement = mappedStatement;
        this.boundSql = boundSql;
        this.param = param;
    }

    @Override
    public void setParameters(PreparedStatement statement) throws SQLException {
        List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
        //判断类型
        Class<?> clazz = param.getClass();
        if (SimpleTypeRegistry.isSimpleType(clazz)) {
            // todo 可以通过类型处理器处理set，如setInt
            statement.setObject(1, param);
        } else if (SimpleTypeRegistry.isMap(param.getClass())) {
            Map params = (Map) param;
            for (int i = 0; i < parameterMappings.size(); i++) {
                ParameterMapping mappingName = parameterMappings.get(i);
                statement.setObject(i + 1, params.get(mappingName));
            }
        } else if (SimpleTypeRegistry.isList(clazz)) {
            // todo 可补充列表参数处理
        } else {
            // 普通对象类型
            for (int i = 0; i < parameterMappings.size(); i++) {
                ParameterMapping mappingName = parameterMappings.get(i);
                // 这边直接通过ognl表达式，支持 user.id的方式获取属性值
                Object value = OgnlUtils.getValue(mappingName.getParameterName(), param);
                statement.setObject(i + 1, value);
            }
        }
    }
}
